/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.asseco.mio.codex.controllers;

import com.asseco.mio.UserInstitution;
import com.asseco.mio.WorkPosition;
import com.asseco.mio.codex.EmploymentReason;
import com.asseco.mio.codex.LeaveReason;
import com.asseco.mio.codex.WorkPositionForm;
import com.asseco.mio.core.webapp.controller.BaseFormController;
import com.asseco.mio.search.UserSearch;
import com.asseco.persistence.service.HibernateUtil;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.appfuse.model.User;
import org.appfuse.service.GenericManager;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author filip.apostolski
 */
@Controller
@RequestMapping("/workpositionsearch*")
public class SearchWorkPositionController extends BaseFormController {

    private GenericManager<WorkPosition, String> workPositionManager;
    private GenericManager<LeaveReason, String> leaveReasonManager;
    private GenericManager<EmploymentReason, String> emplReasonManager;

    @Autowired
    public void setWorkPositionManager(@Qualifier("workPositionManager") GenericManager<WorkPosition, String> workPositionManager) {
        this.workPositionManager = workPositionManager;
    }
    //  private GenericManager<BasicInfo, String> basicInfoManager;
//    @Autowired
//    UserManager userManager;

//    @Autowired
//    public void setBasicInfoManager(@Qualifier("basicInfoManager") GenericManager<BasicInfo, String> basicInfoManager) {
//        this.basicInfoManager = basicInfoManager;
//    }
    @Autowired
    public void setLeaveReasonManager(@Qualifier("leaveReasonManager") GenericManager<LeaveReason, String> leaveReasonManager) {
        this.leaveReasonManager = leaveReasonManager;
    }

    @Autowired
    public void setEmplReasonManager(@Qualifier("employmentReasonManager") GenericManager<EmploymentReason, String> emplReasonManager) {
        this.emplReasonManager = emplReasonManager;
    }

    public List getWorkPosition(WorkPosition workPosition, User user) {
        if (workPosition == null) {
            return null;
        }
        if (workPosition.getEmployment().getFirstName().equals("") && workPosition.getEmployment().getLastName().equals("") && workPosition.getEmployment().getSocScrNo().equals("") && workPosition.getPosition().equals("") && workPosition.getDiscriminator().equals("") && workPosition.getExperience().equals("") && workPosition.getEmplReason().getId().equals("")&&workPosition.getStartDate()==null) {
            return null;
        }
        String pamFirstName = "%";
        String pamLastName = "%";
        String pamSocScrNo = "%";
        String pamEmplReason = "";
        String pamLeaveReason = "";
        String pamPositon = "%";
        String pamExperience = "";
        String pamDate = "";
        String pamDiscriminator = "%";
        List result = new ArrayList();


        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();


        if (workPosition.getEmployment().getFirstName() != null) {
            if (!workPosition.getEmployment().getFirstName().equals("")) {
                pamFirstName = "%" + workPosition.getEmployment().getFirstName() + "%";
            }
        }
        if (workPosition.getEmployment().getLastName() != null) {
            if (!workPosition.getEmployment().getLastName().equals("")) {
                pamLastName = "%" + workPosition.getEmployment().getLastName() + "%";
            }
        }
        if (workPosition.getEmployment().getSocScrNo() != null) {
            if (!workPosition.getEmployment().getSocScrNo().equals("")) {
                pamSocScrNo = "%" + workPosition.getEmployment().getSocScrNo() + "%";
            }
        }
        if (workPosition.getPosition() != null) {
            if (!workPosition.getPosition().equals("")) {
                pamPositon = "%" + workPosition.getPosition() + "%";
            }
        }
        if (workPosition.getExperience() != null) {
            if (!workPosition.getExperience().equals("")) {
                pamExperience = " and workPos.experience like '%" + workPosition.getExperience() + "%' ";
            }
        }
        if (workPosition.getDiscriminator() != null) {
            if (!workPosition.getDiscriminator().equals("")) {
                if (workPosition.getDiscriminator().length() == 7) {
                    pamDiscriminator = "1";
                } else {
                    pamDiscriminator = "0";
                }            
            }
        }

        if (workPosition.getEmplReason() != null) {
            if (!workPosition.getEmplReason().getId().equals("")) {
                EmploymentReason er = emplReasonManager.get(workPosition.getEmplReason().getId());
                workPosition.setEmplReason(er);
                pamEmplReason = " workPos.emplReason.name like '" + workPosition.getEmplReason().getName() + "' and ";
            }
        }

                if (workPosition.getLeaveReason() != null) {
            if (!workPosition.getLeaveReason().getId().equals("")) {
                LeaveReason lr = leaveReasonManager.get(workPosition.getLeaveReason().getId());
                workPosition.setLeaveReason(lr);
                pamLeaveReason = " workPos.leaveReason.name like '" + workPosition.getLeaveReason().getName() + "' and ";
            }
        }

        if (workPosition.getStartDate() != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String date = dateFormat.format(workPosition.getStartDate());
            pamDate = " workPos.startDate =  '" + date + "' and ";
        }


        Query q = session.createQuery("from WorkPosition workPos where "
                + " workPos.institution in (:parameter) and ( "
                +  pamEmplReason
                + pamLeaveReason
                + " workPos.position like '" + pamPositon + "'  "
                + pamExperience
              
                + " and workPos.discriminator like '" + pamDiscriminator + "'  "
                + " and workPos.employment.firstName like '" + pamFirstName + "'  "
                + " and workPos.employment.lastName like '" + pamLastName + "' and "
                + pamDate
                + " workPos.employment.socScrNo like '" + pamSocScrNo + "')");

        UserInstitution ui = new UserInstitution();
        List instList = ui.getInstitutionsForUser(user);
        q.setParameterList("parameter", instList);


        List tempResult = q.list();

        for (int j = 0; j < tempResult.size(); j++) {
            WorkPosition object = (WorkPosition) tempResult.get(j);
            result.add(object);
        }
        session.getTransaction().commit();
        return result;
    }

    @ModelAttribute
    public WorkPositionForm workPositionForm() {
        WorkPositionForm x = new WorkPositionForm(null, null, null, emplReasonManager.getAll(), leaveReasonManager.getAll());
        return x;
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView doSubmit(WorkPositionForm workPositionForm, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        String userString = request.getRemoteUser();
        User user = UserSearch.getUserByUserName(userString);

        WorkPositionForm x = this.workPositionForm();
        if (workPositionForm.getWorkPosition() != null) {
            x.setWorkPosition(workPositionForm.getWorkPosition());
        } else {
            x.setWorkPosition(null);
        }

        return new ModelAndView("workpositionsearch", "workpositionList", this.getWorkPosition(x.getWorkPosition(), user));
    }
    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        super.initBinder(request, binder);
        SimpleDateFormat dateFormat =
                new SimpleDateFormat(getText("dd/MM/yyyy", request.getLocale()));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
    }
}
